package com.authority.framework.web.controller;

import com.authority.framework.log.Log;
import com.authority.framework.log.enums.BusinessType;
import com.authority.framework.web.domain.SysDeptEntity;
import com.authority.framework.web.domain.SysPostEntity;
import com.authority.framework.web.domain.SysRoleEntity;
import com.authority.framework.web.domain.SysUserEntity;
import com.authority.framework.web.service.SysDeptService;
import com.authority.framework.web.service.SysPostService;
import com.authority.framework.web.service.SysRoleService;
import com.authority.framework.web.service.SysUserService;
import com.authority.framework.base.util.*;
import com.authority.framework.base.util.laydata.LayDatas;
import com.authority.framework.base.util.laydata.PageUtils;
import com.authority.framework.base.util.laydata.ResultModel;
import com.authority.framework.base.util.laydata.ResultTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authority.framework.base.util.EncryptPassword.encryptPassword;

/**
 * @program: authority
 * @description: 用户控制层
 * @author: Mr.Yan
 * @create: 2018-11-16 15:51
 **/
@Controller
@RequestMapping(value = "/sysuserCon")
public class SysUserController {
    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
    // 密码加密方式
    @Value("${shiro.user.hashAlgorithmName}")
    private String hashAlgorithmName;

    // 密码加密次数
    @Value("${shiro.user.hashIterations}")
    private Integer hashIterations;

    // 初始密码
    @Value("${shiro.user.initialPass}")
    private String initialPass;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPostService sysPostService;

    private Map<String, Object> paramMap;//参数

    private Map<String, Object> resultMap;//返回值

    /**
     * 查询用户信息
     *
     * @param request
     * @param response
     * @param pageUtils
     * @return
     */

    @RequestMapping("/list")
    @ResponseBody
    public LayDatas list(HttpServletRequest request, HttpServletResponse response,
                         PageUtils pageUtils) {
        //  获取登陆用户信息
        SysUserEntity userEntity = ShiroUtils.getSubjectUser();
        if (!userEntity.isAdmin()) {
            pageUtils.setPara("roleIds", userEntity.getRoleIds());
        }
        return sysUserService.pageLayInfo("system/SysUserSql", SysUserEntity.class, pageUtils);
    }

    /**
     * 添加用户
     *
     * @param request
     * @param response
     * @param ajaxMap
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @RequestMapping("/insert")
    @ResponseBody
    public ResultModel insert(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam Map<String, Object> ajaxMap) {
        try {

            String postIds = (String) ajaxMap.get("postIds");
            String roledIds = (String) ajaxMap.get("roleIds");
            //  获取登陆用户信息
            SysUserEntity userEntity = ShiroUtils.getSubjectUser();
            ajaxMap.put("createBy", userEntity.getUserName());
            //  获取当前时间
            String time = DateUtils.getTime();
            ajaxMap.put("createTime", time);

            //  用户密码加密
            String password = encryptPassword(hashAlgorithmName, new String(ajaxMap.get("password").toString()), null, hashIterations);
            ajaxMap.put("password", password);

            //  添加用户
            Integer userId = sysUserService.insert(SysUserEntity.class, ajaxMap);
            //  添加用户的岗位
            if (StringUtils.isNotEmpty(postIds)) {
                String[] postIdSplit = postIds.split(",");
                for (int i = 0; i < postIdSplit.length; i++) {
                    paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("postId", postIdSplit[i]);
                    //  添加用户和岗位关系
                    try {
                        Integer insertSysUserRole = sysUserService.commonInsert("system/SysUserPost.insertSysUserPost", paramMap);
                        if (insertSysUserRole < 1) {
                            return ResultTools.result(404, "添加用户岗位''失败", null);
                        }
                    } catch (Exception e) {
                        return ResultTools.result(404, "添加用户岗位''失败", null);
                    }
                }
            }
            //  添加用户的角色
            if (StringUtils.isNotEmpty(roledIds)) {
                String roleNames = (String) ajaxMap.get("roleNames");
                String[] roleIdSplit = roledIds.split(",");
                String[] roleNamesSplit = roleNames.split(",");
                for (int i = 0; i < roleIdSplit.length; i++) {
                    paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("roleId", roleIdSplit[i]);
                    //  添加用户和角色关系
                    try {
                        Integer insertSysUserRole = sysUserService.commonInsert("system/SysUserRole.insertSysUserRole", paramMap);
                        if (insertSysUserRole < 1) {
                            return ResultTools.result(404, "添加用户角色'" + roleNamesSplit[i] + "'失败", null);
                        }
                    } catch (Exception e) {
                        return ResultTools.result(404, "添加用户角色'" + roleNamesSplit[i] + "'失败", null);
                    }
                }
            }
            return ResultTools.result(0, "", null);
        } catch (Exception e) {
            log.error("添加用户信息出现错误" + e.getMessage());
            return ResultTools.result(404, "添加用户信息出现未知错误", null);
        }
    }

    /**
     * @Description: 打开修改用户信息界面之前，获取用户详细信息
     * @Param:
     * @return:
     * @Author: Mr.Yan
     * @Date: 2018/12/7
     */
    @ResponseBody
    @RequestMapping(value = "/openUserUpdate")
    public ModelAndView openUserUpdate(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(name = "userId", required = false) Integer userId) {
        resultMap = new HashMap<>();
        // 查询用户表信息
        SysUserEntity userEntity = sysUserService.findByPrimaryKey(SysUserEntity.class, userId);
        // 查询用户部门信息
        SysDeptEntity deptEntity = sysDeptService.findByPrimaryKey(SysDeptEntity.class, userEntity.getDeptId().intValue());
        // 查询用户角色信息
        List<SysRoleEntity> roleEntitys = sysRoleService.findListByUserId(userId);
        String roleIds = "";
        String roleNames = "";
        if (roleEntitys.size() > 0) {
            for (SysRoleEntity role : roleEntitys) {
                roleIds += role.getRoleId() + ",";
                roleNames += role.getRoleName() + ",";
            }
            roleIds = roleIds.substring(0, roleIds.length() - 1);
            roleNames = roleNames.substring(0, roleNames.length() - 1);
        }

        // 向前台传递 角色 id 和 名称用',' 分割
        resultMap.put("roleIds", roleIds);
        resultMap.put("roleNames", roleNames);
        //  查询用户岗位信息
        paramMap = new HashMap<>();
        paramMap.put("user_Id", userId);
        List<SysPostEntity> postEntities = sysPostService.findListByUserId(userId);
        String postIds = "";
        String postNames = "";
        if (postEntities.size() > 0) {
            for (SysPostEntity post : postEntities) {
                postIds += post.getPostId() + ",";
                postNames += post.getPostName() + ",";
            }
            postIds = postIds.substring(0, postIds.length() - 1);
            postNames = postNames.substring(0, postNames.length() - 1);
        }

        // 向前台传递 角色 id 和 名称用',' 分割
        resultMap.put("postIds", postIds);
        resultMap.put("postNames", postNames);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("web/system/user/user_update");
        mv.addObject("user", userEntity);
        mv.addObject("dept", deptEntity);
        mv.addObject("other", resultMap);
        return mv;
    }

    /**
     * @Description: 更新用户信息
     * @Param:
     * @return:
     * @Author: Mr.Yan
     * @Date: 2018/12/7
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @ResponseBody
    @RequestMapping(value = "/update")
    public ResultModel update(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam Map<String, Object> ajaxMap) {
        try {

            String userId = (String) ajaxMap.get("userId");
            String postIds = (String) ajaxMap.get("postIds");
            String roledIds = (String) ajaxMap.get("roleIds");
            //  获取当前时间
            String time = DateUtils.getTime();
            //  获取登陆用户信息
            SysUserEntity userEntity = ShiroUtils.getSubjectUser();
            ajaxMap.put("updateBy", userEntity.getUserName());
            ajaxMap.put("updateTime", time);
            //  更新用户
            Integer isUpdate = sysUserService.update(SysUserEntity.class, ajaxMap);
            //删除用户以前岗位
            Integer deleteUserPostSize = sysUserService.deleteUserPost(userId);
            //  添加用户的岗位
            if (StringUtils.isNotEmpty(postIds)) {
                String[] postIdSplit = postIds.split(",");
                for (int i = 0; i < postIdSplit.length; i++) {
                    paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("postId", postIdSplit[i]);
                    //  添加用户和岗位关系
                    try {
                        Integer insertSysUserRole = sysUserService.commonInsert("system/SysUserPost.insertSysUserPost", paramMap);
                        if (insertSysUserRole < 1) {
                            return ResultTools.result(404, "更新用户岗位''失败", null);
                        }
                    } catch (Exception e) {
                        return ResultTools.result(404, "更新用户岗位''失败", null);
                    }
                }
            }
            //删除用户以前角色
            Integer deleteUserRoleSize = sysUserService.deleteUserRole(userId);
            //  添加用户的角色
            if (StringUtils.isNotEmpty(roledIds)) {
                String roleNames = (String) ajaxMap.get("roleNames");
                String[] roleIdSplit = roledIds.split(",");
                String[] roleNamesSplit = roleNames.split(",");
                for (int i = 0; i < roleIdSplit.length; i++) {
                    paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("roleId", roleIdSplit[i]);
                    //  添加用户和角色关系
                    try {
                        Integer insertSysUserRole = sysUserService.commonInsert("system/SysUserRole.insertSysUserRole", paramMap);
                        if (insertSysUserRole < 1) {
                            return ResultTools.result(404, "更新用户角色'" + roleNamesSplit[i] + "'失败", null);
                        }
                    } catch (Exception e) {
                        return ResultTools.result(404, "更新用户角色'" + roleNamesSplit[i] + "'失败", null);
                    }
                }
            }
            return ResultTools.result(0, "", null);
        } catch (Exception e) {
            log.error("更新用户信息出现未知错误" + e.getMessage());
            return ResultTools.result(404, "更新用户信息出现未知错误", null);
        }
    }

    /**
     * 删除 用户信息
     *
     * @param request
     * @param response
     * @param userIds
     * @return
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @ResponseBody
    @RequestMapping(value = "/deleteUser")
    public ResultModel deleteUser(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(name = "userIds", required = false) String userIds) {
        try {
            String[] userIdArr = userIds.split(",");
            for (String userId : userIdArr) {
                paramMap = new HashMap<>();
                paramMap.put("userId", userId);
                paramMap.put("delFlag", 2);
                //  获取当前时间
                String time = DateUtils.getTime();
                //  获取登陆用户信息
                SysUserEntity userEntity = ShiroUtils.getSubjectUser();
                paramMap.put("updateTime", time);
                paramMap.put("updateBy", userEntity.getUserName());
                Integer update = sysUserService.update(SysUserEntity.class, paramMap);
                if (update < 1) {
                    return ResultTools.result(404, "删除用户信息失败", null);
                }
            }
            return ResultTools.result(0, "", null);
        } catch (Exception e) {
            log.error("删除用户信息出现未知错误" + e.getMessage());
            return ResultTools.result(404, "删除用户信息出现未知错误", null);
        }
    }

    /**
     * 重置密码
     *
     * @param request
     * @param response
     * @param userId
     * @return
     */
    @Log(title = "重置密码", businessType = BusinessType.operatePass)
    @ResponseBody
    @RequestMapping(value = "operatePass")
    public ResultModel operatePass(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(name = "userId", required = false) String userId) {
        try {
            paramMap = new HashMap<>();
            paramMap.put("userId", userId);
            //  获取当前时间
            String time = DateUtils.getTime();
            //  获取登陆用户信息
            SysUserEntity userEntity = ShiroUtils.getSubjectUser();
            paramMap.put("updateTime", time);
            paramMap.put("updateBy", userEntity.getUserName());
            String password = encryptPassword(hashAlgorithmName, new String(initialPass), null, hashIterations);
            paramMap.put("password", password);
            Integer update = sysUserService.update(SysUserEntity.class, paramMap);
            if (update < 1) {
                return ResultTools.result(404, "重置用户密码失败", null);
            }
            return ResultTools.result(0, "", null);
        } catch (Exception e) {
            log.error("重置用户密码出现未知错误" + e.getMessage());
            return ResultTools.result(404, "删除用户信息出现未知错误", null);
        }
    }

    /**
     * @Author: Mr.Yan
     * @Date: 2019/1/11
     * @MethodName: changePass
     * @Description: 修改密码
     * @Param: [request, response, userId, oldPassWord, newPassWord, newPassWordIsOk]
     * @return: com.authority.framework.base.util.laydata.ResultModel
     */
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @ResponseBody
    @RequestMapping(value = "/changePass")
    public ResultModel changePass(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(name = "userId", required = false) Integer userId,
                                  @RequestParam(name = "oldPassWord", required = false) String oldPassWord,
                                  @RequestParam(name = "newPassWord", required = false) String newPassWord,
                                  @RequestParam(name = "newPassWordIsOk", required = false) String newPassWordIsOk) {
        try {
            SysUserEntity userEntity = sysUserService.findByPrimaryKey(SysUserEntity.class, userId);
            // 前台输入旧密码加密
            String oldEncryptPassword = encryptPassword(hashAlgorithmName, oldPassWord, null, hashIterations);
            // 验证旧密码是否相同
            if(!oldEncryptPassword.equals(userEntity.getPassword())){
                return ResultTools.result(404, "输入旧密码不正确", null);
            }
            // 验证输入两次密码是否相同
            if(!newPassWord.equals(newPassWordIsOk)){
                return ResultTools.result(404, "输入两次新密码不相同", null);
            }
            // 前台输入确认密码加密
            String newEncryptPassword = encryptPassword(hashAlgorithmName, newPassWordIsOk, null, hashIterations);
            paramMap = new HashMap<>();
            paramMap.put("userId",userId);
            paramMap.put("password",newEncryptPassword);
            Integer update = sysUserService.update(SysUserEntity.class, paramMap);
            if (update < 1) {
                return ResultTools.result(404, "修改密码失败", null);
            }
            return ResultTools.result(0, "", null);
        } catch (Exception e) {
            log.error("修改密码出现未知错误" + e.getMessage());
            return ResultTools.result(404, "修改密码出现未知错误", null);
        }
    }


}
